package com.love.web.session.filter;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class StandardManager implements Manager{
	
	protected SessionIdGenerator sessionIdGenerator = new StandardSessionIdGenerator();
	
	protected HttpServletRequest request;
	
	protected HttpServletResponse response;
	
	protected Store store;
	
	public StandardManager(HttpServletRequest request, HttpServletResponse response, Store store){
		this.request = request;
		this.response = response;
		this.store = store;
	}

	public ServletContext getContext() {
		return SessionContext.filterConfig.getServletContext();
	}

	public SessionIdGenerator getSessionIdGenerator() {
		return this.sessionIdGenerator;
	}

	public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) {
		this.sessionIdGenerator = sessionIdGenerator;
	}

	public Session createEmptySession() {
		Session session = new StandardSession(this);
        session.setMaxInactiveInterval(SessionContext.maxInactiveInterval);
        saveCookie(session, request, response);
        return session;
	}
	
	private void saveCookie(Session session, HttpServletRequest request, HttpServletResponse response) {
        Cookie cookie = new Cookie(SessionConstants.SESSION_ID_COOKIE, null);
        cookie.setPath(request.getContextPath());
        cookie.setValue(session.getId());
        response.addCookie(cookie);
    }

	public Session findSession(String sessionId) {
		if(sessionId == null){
			return null;
		}
		return store.getSession(sessionId);
	}

	public void remove(String sessionId) {
		store.deleteSession(sessionId);
	}

	public void saveSession(String sessionId, Session session){
		if(session.isExpiring()){
			store.deleteSession(sessionId);
			return;
		}
		if(SessionContext.maxInactiveInterval <= 0){
			if(session.isNew()){
				store.setSession(sessionId, session);
				return;
			}
			if(session.isDirty()){
				store.setSession(sessionId, session);
				return;
			}
		}else{
			if(session.isNew()){
				store.setSession(sessionId, session, SessionContext.maxInactiveInterval);
				return;
			}
			if(session.isDirty()){
				store.setSession(sessionId, session, SessionContext.maxInactiveInterval);
				return;
			}
			store.expireSession(sessionId, SessionContext.maxInactiveInterval);
		}
		
	}

}
